package cn.schoolwow.quickdao.test.module.business.user.ddl.testcase;

import cn.schoolwow.quickdao.annotation.IndexType;
import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.database.ddl.IndexField;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.test.entity.User;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.junit.Assert;

import java.util.Arrays;

public class CreateNumberColumnUniqueIndexTestCaseFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        flowContext.executeFlowList(new CreateNumberColumnTestCaseFlow());
        createNumberColumnUniqueIndex(flowContext);
        checkCreateNumberColumnIndexResult(flowContext);
    }

    @Override
    public String name() {
        return "检查用户表工号字段添加唯一性约束用例";
    }

    private void createNumberColumnUniqueIndex(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        Entity userEntity = dao.getEntity(User.class);

        IndexField indexField = new IndexField();
        indexField.tableName = userEntity.tableName;
        indexField.comment = "工号唯一性约束";
        indexField.indexType = IndexType.UNIQUE;
        indexField.columns = Arrays.asList("number");
        dao.createIndex(indexField);

        flowContext.putTemporaryData("indexField", indexField);
    }

    private void checkCreateNumberColumnIndexResult(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        IndexField indexField = (IndexField) flowContext.checkData("indexField");

        IndexField numberIndexField = dao.getIndexField(indexField.tableName, indexField.indexName);
        Assert.assertNotNull(numberIndexField);
        Assert.assertEquals(indexField.indexType, numberIndexField.indexType);
        Assert.assertEquals(indexField.columns, numberIndexField.columns);
    }
}
